import GameConfig from '../config/GameConfig.js';
import SoundManager from '../utils/SoundManager.js';
/**
 * 蛇类
 */
export default class Snake {
    /**
     * 初始化蛇
     */
    constructor() {
        this.reset();
    }

    /**
     * 重置蛇的状态
     */
    reset() {
        this.segments = [{x: 5, y: 5}];
        this.direction = 'right';
        this.nextDirection = 'right';
        this.growing = false;
    }

    /**
     * 移动蛇
     * @param {Food} food - 食物对象
     * @returns {boolean} 是否吃到食物
     */
    move() {
      const head = { ...this.segments[0] };
    
      switch(this.direction) {
          case 'up': head.y--; break;
          case 'down': head.y++; break;
          case 'left': head.x--; break;
          case 'right': head.x++; break;
      }
  
      this.segments.unshift(head);
      
      if (!this.growing) {
          this.segments.pop();
      }
      this.growing = false;

      // 添加移动音效
      SoundManager.play('move');
  
      return head;
    }

    /**
     * 让蛇增长
     */
    grow() {
        this.growing = true;
    }

    /**
 * 检查碰撞
 * @param {Object} gameDimensions - 游戏区域尺寸
 * @returns {boolean} 是否发生碰撞
 */
checkCollision(gameDimensions) {
  const head = this.segments[0];
  
  // 检查是否撞墙
  if (head.x < 0 || 
      head.x >= gameDimensions.width || 
      head.y < 0 || 
      head.y >= gameDimensions.height) {
      return true;
  }

  // 检查是否撞到自己
  return this.segments.slice(1).some(segment => 
      segment.x === head.x && segment.y === head.y
  );
}

    /**
     * 设置方向
     * @param {string} newDirection - 新方向
     */
    setDirection(newDirection) {
        const opposites = {
            'up': 'down',
            'down': 'up',
            'left': 'right',
            'right': 'left'
        };

        if (opposites[newDirection] !== this.direction) {
            this.nextDirection = newDirection;
        }
    }

    /**
     * 更新蛇的状态
     */
    update() {
        this.direction = this.nextDirection;
    }

    /**
     * 获取蛇头
     * @returns {Object} 蛇头坐标
     */
    getHead() {
        return this.segments[0];
    }
}